from dataclasses import dataclass
import json


@dataclass
class Student:
    name: str = ""
    age: int = 0
    address: str = ""

    def __str__(self):
        """格式化成json字符串"""
        return json.dumps(self.__dict__)

    def parse_str(self, orig: str):
        """从json字符串解析"""
        data = json.loads(orig)
        for k, v in data.items():
            # setattr(self, name, value) 通过字符串, 匹配类成员变量, 并赋值
            setattr(self, k, v)
        return self


if __name__ == "__main__":
    tom = Student("Tom", 18, "Beijing")
    tom.name = "new_Tom"

    json_str = str(tom)
    new_tom = Student().parse_str(json_str)
    print(new_tom)

""" 
{"name": "new_Tom", "age": 18, "address": "Beijing"}
"""
